﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsForm
{
    public partial class Form1 : Form
    {
        private System.ServiceModel.ServiceHost host;

        public Form1()
        {
            InitHost();
            InitializeComponent();
        }

        private void InitHost()
        {
            host = new System.ServiceModel.ServiceHost(typeof(WcfServiceLibraryPbMetaData.Service1));
            host.Closed += new EventHandler(host_Closed);
            host.Closing += new EventHandler(host_Closing);
            host.Faulted += new EventHandler(host_Faulted);
            host.Opened += new EventHandler(host_Opened);
            host.Opening += new EventHandler(host_Opening);
            host.UnknownMessageReceived += new EventHandler<System.ServiceModel.UnknownMessageReceivedEventArgs>(host_UnknownMessageReceived);
        }

        void host_UnknownMessageReceived(object sender, System.ServiceModel.UnknownMessageReceivedEventArgs e)
        {
            try
            {
                label1.Text = "Unknown message received" + e.Message;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        void host_Opening(object sender, EventArgs e)
        {
            label1.Text = "Opening...";
            button1.Text = "Close";
        }

        void host_Opened(object sender, EventArgs e)
        {
            label1.Text = "Opened";
            button1.Text = "Close";
            listBox1.Items.Clear();
            foreach (System.ServiceModel.Description.ServiceEndpoint ep in host.Description.Endpoints) 
            {
                listBox1.Items.Add(ep.Name + " - " + ep.Address);
            }
        }

        void host_Faulted(object sender, EventArgs e)
        {
            label1.Text = "Faulted";
            button1.Text = "Close";
        }

        void host_Closing(object sender, EventArgs e)
        {
            label1.Text = "Closing...";
        }

        void host_Closed(object sender, EventArgs e)
        {
            label1.Text = "Closed";
            button1.Text = "Open";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (((Button)sender).Text == "Close")
            {
                this.host.Close();
            }
            else
            {
                if (this.host.State != System.ServiceModel.CommunicationState.Created)
                {
                    this.InitHost();
                }
                this.host.Open();
            }
        }
    }
}
